const AuthException = require('../exception/authException');
const { httpCode } = require('../utils/userConfig')
module.exports = currentOperator => {

    return async function auth(ctx, next) {
        const path = ctx.path;
        const from = ctx.header.from;
        if (!['/login', '/videos/logs/monitoring'].includes(path)) {
            const { from } = ctx.header;
            if (from === 'web') {
                // 获取token   
                const rolesToken = ctx.cookies.get('roles', {
                    signed: false
                });
                const token = ctx.cookies.get('token', {
                    signed: false
                });
                // 验证token
                const { userId, userName, roles, appId } = await ctx.service.sys.user.verifyToken(token, rolesToken);
                // 将用户id添加到ctx上 
                ctx.currentUserId = userId;
                ctx.appId = appId;
                ctx.currentUserName = userName;
                if (path != '/sys/getUserInfo') {
                    await checkAuth(userId, roles, ctx);
                }
                ctx.from = from;
                await next();
            } else if (from === 'guaguaApp') {
                let { app } = ctx;
                let { wxappid, dyappid, secret, token } = ctx.header;
                // if (path != "/wx/login") {
                //     if (!secret) {
                //         throw new AuthException(
                //             "权限不足，请不要恶意攻击1，如有需要请联系微信:TheHelloWorld",
                //             httpCode.LOGINEXPIREERROR
                //         );
                //     }
                //     await app.jwt.verify(secret, app.config.jwt.secret);
                //     const validateToken = await app.jwt.decode(secret);
                //     if (token != validateToken.id) {
                //         throw new AuthException(
                //             "权限不足，请不要恶意攻击2\，如有需要请联系微信:TheHelloWorld",
                //             httpCode.LOGINEXPIREERROR
                //         );
                //     }
                // }
                // let verifyApp = await ctx.service.sys.user.verifyApp(wxappid);
                // if (!verifyApp) {
                //     throw new AuthException(
                //         "小程序登录异常，信息配置异常",
                //         httpCode.LOGINEXPIREERROR
                //     );
                // }
                // const { id: userId, userName, wxAppId, wxAppSecret } = verifyApp;
                // ctx.currentUserId = userId;
                // ctx.currentUserName = userName;
                // ctx.appId = wxAppId;
                // ctx.appSecret = wxAppSecret;
                ctx.from = from;
                await next();
            }
        } else {
            await next();
        }
    }

    async function checkAuth(userId, roles, ctx) {
        if (Object.keys(currentOperator).length === 0 || userId === 'bb36d6d1-f20c-4c93-a094-16666666688') {
            return true;
        }
        if (!roles || !userId) {
            throw new AuthException("无用户相关信息！", httpCode.LOGINEXPIREERROR);
        }
        const hasAccess = roles.includes(currentOperator);
        if (!hasAccess) {
            throw new AuthException('权限不足，请联系管理员', httpCode.AUTHORITYEERROR);
        }
    }
}